<template>
  <div>
    <div v-if="reloading">
      <span> Reloading... </span>
    </div>
    <area-cascader
      v-else
      v-model="innerValue"
      :data="pcaa"
      :level="level"
      @change="handleChange"
    ></area-cascader>
  </div>
</template>

<script>
import { pca, pcaa } from "area-data";
import Area from "@/components/_util/Area";
export default {
  name: "EryuArea",
  props: {
    options: {
      type: Array,
      default: null,
    },
    // 传入区的code 可通过区的code反推完整省市区
    value: {
      type: String,
      default: "",
    },
    // 选择的区域等级 默认为1 及可选择省市区
    level: {
      type: Number,
      default: 1,
    },
  },
  computed: {},
  data() {
    return {
      innerValue: [],
      pcaa: this.$Erpcaa,
      areaData: "",
      reloading: false,
    };
  },

  watch: {
    value: {
      immediate: true,
      handler() {
        this.loadDataByValue(this.value);
      },
    },
  },
  created() {
    this.initAreaData();
  },

  methods: {
    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area(this.$Erpcaa);
      }
    },

    reload() {
      this.reloading = true;
      this.$nextTick(() => (this.reloading = false));
    },

    /** 通过 value 反推 options */
    loadDataByValue(value) {
      if (!value || value.length === 0) {
        this.innerValue = [];
      } else {
        this.initAreaData();
        let arr = this.areaData.getRealCode(value, this.level);
        this.innerValue = arr;
      }
      this.reload();
    },
    /** 通过地区code获取子级 */
    loadDataByCode(value) {
      let options = [];
      let data = this.pcaa[value];
      if (data) {
        for (let key in data) {
          if (data.hasOwnProperty(key)) {
            options.push({ value: key, label: data[key] });
          }
        }
        return options;
      } else {
        return [];
      }
    },
    handleChange(values) {
      let value = values[values.length - 1];

      if (!!value) {
        let allCode = this.areaData.getNameByCode(value, this.level);
        let codeNames = allCode.map((item) => {
          return item.text;
        });

        let obj = {
          provinces: allCode[0] ? allCode[0].id : "",
          city: allCode[1] ? allCode[1].id : "",
          area: allCode[2] ? allCode[2].id : "",
        };
        this.$emit("changeAll", obj, codeNames.join(","), allCode);
      }

      this.$emit("change", value);
    },
  },

  model: { prop: "value", event: "change" },
};
</script>
<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>